package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.PressSingleBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.activity.WebViewActivity;
import com.zahb.qadx.ui.view.decoration.MDividerItemDecoration;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by： huwei.
 * Data： 2020-10-27.
 * Time： 15:12.
 * Desc：新闻导航
 */
public class NewsItemFragment extends BaseFragmentExt implements OnRefreshLoadMoreListener {

    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    private NewsAdapter adapter;
    private int id;
    private int page = 1;
    private boolean mIsFirstLoad = true;
    private boolean mIsFirst = true;
    private MDividerItemDecoration mItemDecoration;
    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;
    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstLoad) {
            mIsFirstLoad = false;
            id = mArguments.getInt("id", -1);
            getCateList(1);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_my_news_list;
    }

    @Override
    protected void initViews(View rootView) {
        mUnbinder = ButterKnife.bind(this, rootView);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        if (adapter == null) {
            adapter = new NewsAdapter(R.layout.fragment_my_news_list_item);
        }
        adapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra("type", "1");
            intent.putExtra("id", NewsItemFragment.this.adapter.getItem(position).getNewsId());
            startActivity(intent);
        });
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        adapter.setEmptyView(emptyView);
        LinearLayoutManager manager = new LinearLayoutManager(requireActivity());
        manager.setOrientation(RecyclerView.VERTICAL);
        recycler_view.setLayoutManager(manager);
        recycler_view.setAdapter(adapter);
        mItemDecoration = new MDividerItemDecoration(getContext());
    }

    /**
     * 获取新闻分类列表
     */
    private void getCateList(int page) {
//        Gson mGson = new Gson();
//        Map<String, Object> map = new HashMap<>();
//        map.put("pageSize", 10);
//        map.put("pageNo", page);
//        map.put("isPublish", 1);
//        map.put("listType", 0);
//        if (id != -1)
//            map.put("cateId", id);
//        RequestBody body = RequestBody.create(MediaType.parse("application/json"), mGson.toJson(map));
//        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
//            if (mIsFirst) {
//                showProgressDialog("数据加载中...");
//                mIsFirst = false;
//            }
//            addDisposable(RetrofitService.getNetService()
//                    .getNewsListData(body)
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(response -> {
//                        if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
//                            mRefreshLayout.finishRefresh();
//                        if (mRefreshLayout != null && mRefreshLayout.isLoading())
//                            mRefreshLayout.finishLoadMore(1000);
//                        hideProgressDialog();
//                        List<CateNavigationModel.NewsDataItem> list = response.getData().getList();
//                        if (page == 1) {
//                            adapter.setList(list);
//                            if (adapter.getData().size() == 0 && recycler_view.getItemDecorationCount() == 1)
//                                recycler_view.removeItemDecoration(mItemDecoration);
//                            if (adapter.getData().size() > 0 && recycler_view.getItemDecorationCount() == 0)
//                                recycler_view.addItemDecoration(mItemDecoration);
//                        } else {
//                            adapter.addData(list);
//                        }
//                    }, throwable -> {
//                        hideProgressDialog();
//                        throwable.printStackTrace();
//                        Tips.RequestError(getActivity());
//                        if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
//                            mRefreshLayout.finishRefresh();
//                        if (mRefreshLayout != null && mRefreshLayout.isLoading())
//                            mRefreshLayout.finishLoadMore(1000);
//                    }));
//        }
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            if (mIsFirst) {
                //showProgressDialog("数据加载中...");
                showSkeleton();
                mIsFirst = false;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("pageSize", 10);
            map.put("pageNo", page);
            if (id != -1){
                map.put("cateId", id);
            }
            addDisposable(RetrofitService.getNetService()
                    .getTheNewsListIsUpdated(map)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                            if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
                                mRefreshLayout.finishRefresh();
                            if (mRefreshLayout != null && mRefreshLayout.isLoading())
                                mRefreshLayout.finishLoadMore(1000);
                            hideProgressDialog();
                            List<PressSingleBean.DataBean.ItemsBean>   list = response.getData().getItems();
                            if (page == 1) {
                                adapter.setList(list);
                                if (adapter.getData().size() == 0 && recycler_view.getItemDecorationCount() == 1)
                                    recycler_view.removeItemDecoration(mItemDecoration);
                                if (adapter.getData().size() > 0 && recycler_view.getItemDecorationCount() == 0)
                                    recycler_view.addItemDecoration(mItemDecoration);
                            } else {
                                adapter.addData(list);
                            }
                        }
                        hideSkeleton();
                    }, throwable -> {
                        hideProgressDialog();
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                        if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
                            mRefreshLayout.finishRefresh();
                        if (mRefreshLayout != null && mRefreshLayout.isLoading())
                            mRefreshLayout.finishLoadMore(1000);
                        hideSkeleton();
                    }));

        }
    }

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(recycler_view)
                .adapter(adapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_curriculum_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
                LiveEventBus.get("hideSkeleton", String.class).post("hideSkeleton");
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getCateList(page);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getCateList(page);
    }

    public static class NewsAdapter extends BaseQuickAdapter<PressSingleBean.DataBean.ItemsBean, BaseViewHolder> {

        private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault());
        private DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        NewsAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, PressSingleBean.DataBean.ItemsBean mainFunc2) {
            String value = "";
            df2.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date date;
            try {
                date = df.parse(mainFunc2.getCreateTime());
                if (date != null)
                    value = df2.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            ImageLoaderKt.loadImageSameCorners(baseViewHolder.getView(R.id.img), mainFunc2.getCoverPath(), 5f);
            baseViewHolder.setText(R.id.title, mainFunc2.getTitle()).setText(R.id.content,mainFunc2.getSubtitle())
                    //.setText(R.id.content, Html.fromHtml(mainFunc2.getContent()))
                    .setText(R.id.time, mainFunc2.getCreateTime());//1.3.4新改动

        }
    }
}
